package com.gamejelly.proxy.client;

import com.gamejelly.proxy.pojo.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

@ChannelHandler.Sharable
public class ClientResponseHandler extends SimpleChannelInboundHandler<RpcResponse> {

    private static final Logger logger = LoggerFactory.getLogger(ClientResponseHandler.class);


    @Setter
    private Connection connection;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String address = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
        logger.info("connect to {} success", address);
        connection.connected();
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        connection.disConnected();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse resp) throws Exception {
        connection.consume(resp);
    }


}
